package site.marqstree.latte.core.ui.scanner;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
import site.marqstree.latte.core.delegates.LatteDelegate;
import site.marqstree.latte.core.util.callback.CallbackManager;
import site.marqstree.latte.core.util.callback.CallbackType;
import site.marqstree.latte.core.util.callback.IGlobalCallback;

/*
 * 项目名: EleCommerce
 * 包名: site.marqstree.latte.core.ui.scanner
 * 文件名: ScannerDelegate
 * 创建者: marqstree
 * 创建时间: 2020/2/8 9:33
 * 描述: 扫描二维码Fragment
 */
public class ScannerDelegate extends LatteDelegate implements ZBarScannerView.ResultHandler {

    private ZBarScannerView mScanView = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mScanView == null) {
            mScanView = new ZBarScannerView(getContext());
        }
        mScanView.setSquareViewFinder(true);
        mScanView.setBorderColor(Color.YELLOW);
        mScanView.setLaserColor(Color.YELLOW);
        mScanView.setAutoFocus(true);
        mScanView.setResultHandler(this);
    }

    @Override
    public Object setLayout() {
        return mScanView;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mScanView != null) {
            mScanView.startCamera();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mScanView != null) {
            mScanView.stopCameraPreview();
            mScanView.stopCamera();
        }
    }

    @Override
    public void handleResult(Result result) {
        //取出并执行业务代码写入的扫描二维码回调接口
        @SuppressWarnings("unchecked")
        final IGlobalCallback<String> callback = CallbackManager
                .getInstance()
                .getCallback(CallbackType.ON_SCAN);
        if (callback != null) {
            callback.executeCallback(result.getContents());
        }
        //将此扫描二维码Fragment弹出栈
        getSupportDelegate().pop();
    }
}
